10. Starter Code

Starter Code

Pluralization in Android

Part of Android’s robust resource framework involves a mechanism for pluralizing strings called “Quantity Strings”. In the strings.xml file for the Hydration Reminder app, you’ll see an example of how pluralization can be used:

<plurals name="charge_notification_count">
   <item quantity="zero">Hydrate while charging reminder sent %d times</item>
   <item quantity="one">Hydrate while charging reminder sent %d time</item>
   <item quantity="other">Hydrate while charging reminder sent %d times</item>
</plurals>

When you use the plural in code, you specify a quantity number. This number specifies what string should be used. In this case:

  • if the number is zero, use <item quantity="zero">
  • If the number is one, use <item quantity="one">
  • otherwise use <item quantity="other">

Then in the MainActivity we have the following Java code to generate the correct String:

String formattedChargingReminders = getResources().getQuantityString(R.plurals.charge_notification_count, chargingReminders, chargingReminders);

The first usage of chargingReminder is the quantity number. It determines which version of the pluralized string to use (you must pass in a number). The second usage of chargingReminder is the number that’s actually inserted into the formatted string.

For more detail on Quantity Strings, check out the documentation